package top.luo.config;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import top.luo.io.Resources;
import top.luo.pojo.Configuration;

import java.beans.PropertyVetoException;
import java.io.InputStream;
import java.util.List;
import java.util.Properties;

/**
 * @author luo
 * @date 2021-01-04 21:10
 */
public class XmlConfigBuilder {

    private final Configuration configuration;

    public XmlConfigBuilder() {
        this.configuration = new Configuration();
    }

    /**
     * 使用 dom4j 对配置文件进行解析，封装 Configuration
     */
    @SuppressWarnings("unchecked")
    public Configuration parse(InputStream ins) throws DocumentException, PropertyVetoException {
        // sqlMapConfig 解析
        Document document = new SAXReader().read(ins);
        Element root = document.getRootElement();
        List<Element> elements = root.selectNodes("//property");

        Properties properties = new Properties();
        for (Element element : elements) {
            properties.setProperty(element.attributeValue("name"), element.attributeValue("value"));
        }

        ComboPooledDataSource pool = new ComboPooledDataSource();
        pool.setDriverClass(properties.getProperty("driverClass"));
        pool.setJdbcUrl(properties.getProperty("jdbcUrl"));
        pool.setUser(properties.getProperty("username"));
        pool.setPassword(properties.getProperty("password"));

        configuration.setDataSource(pool);

        // mapper 解析
        List<Element> mapperlist = root.selectNodes("//mapper");
        for (Element mapper : mapperlist) {
            // 解析 mapper.xml 文件
            XmlMapperBuilder mapperBuilder = new XmlMapperBuilder(configuration);
            mapperBuilder.parse(Resources.getResourceAsStream(mapper.attributeValue("resource")));
        }


        return configuration;
    }

}
